package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.UserDAO;
import com.hanoi.wiki.dao.UserLogDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.UserLogManager;
import com.hanoi.wiki.model.User;
import com.hanoi.wiki.model.UserLog;
import com.hanoi.wiki.model.json.UserLogJson;

@Component
@Transactional
public class UserLogManagerImpl extends BaseManagerImpl implements UserLogManager{
	@Autowired
	private UserLogDAO userLogDAO;
	
	@Autowired
	private UserDAO userDAO;
	
	public int save(UserLogJson json) {
		try {
			UserLog userLog = new UserLog(json);
			
			User user = userDAO.get(json.getUser());
			if(user != null) {
				userLog.setUser(user);
			}
			
			return userLogDAO.saveUserLog(userLog);
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return 0;
	}

	public void update(UserLogJson json) {
		try {
			UserLog userLog = new UserLog(json);

			userLog.setId(json.getId());
			User user = userDAO.get(json.getUser());
			if(user != null) {
				userLog.setUser(user);
			}
			
			userLogDAO.update(userLog);
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}

	public UserLogJson get(Integer id) {
		try {
			return new UserLogJson(userLogDAO.get(id));
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return null;
	}

	public List<UserLogJson> getList() {
		List<UserLogJson> userLogJsonList = new ArrayList<UserLogJson>();
		List<UserLog> userLogList = userLogDAO.getList();
		try {
			for(UserLog userLog : userLogList) {
				userLogJsonList.add(new UserLogJson(userLog));
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return userLogJsonList;
	}

	public void remove(Integer id) {
		try {
			if(userLogDAO.get(id) != null) {
				userLogDAO.remove(id);
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}
}
